package atguigu.flume_kafka_inteceptor;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

public class ETL_interceptor implements Interceptor {
    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
    // 1. 获取body
        String message = new String(event.getBody(), StandardCharsets.UTF_8);
        // 2. 判断是否符合json
        if(Util_json.isJsonString(message)){
            // 3. 符合json格式，在头部插入type:true
            event.getHeaders().put("type","true");
        }
        else
            // 3. 符合json格式，在头部插入type:false
            event.getHeaders().put("type","false");
        return event;
    }

    /**
     * 将不符合要求的events从集合中删除，拦截掉
     * @param eventList
     * @return
     */
    @Override
    public List<Event> intercept(List<Event> eventList) {

        Iterator<Event> error_message = eventList.iterator();

        while (error_message.hasNext()){
            Event event = error_message.next();

            //调用上面的intercept(Event event)方法处理event
            intercept(event);
            String flag = event.getHeaders().get("type");

            if (flag.equals("false")){
                error_message.remove();
            }
        }
        return eventList;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder{

        /**
         * 构建拦截器的方法
         * @return
         */
        @Override
        public Interceptor build() {
            return new ETL_interceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

}
